import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class BirthdaySelector extends StatefulWidget {
  final DateTime? initialBirthday;
  final Function(DateTime) onDateChanged;

  const BirthdaySelector({Key? key, this.initialBirthday, required this.onDateChanged}) : super(key: key);

  @override
  _BirthdaySelectorState createState() => _BirthdaySelectorState();
}

class _BirthdaySelectorState extends State<BirthdaySelector> {
  late DateTime _birthday;

  @override
  void initState() {
    super.initState();
    _birthday = widget.initialBirthday ?? DateTime.now();
  }

  Future<void> _selectDate(BuildContext context) async {
    DateTime initialDate = _birthday;
    DateTime firstDate = DateTime(1900);
    DateTime lastDate = DateTime.now();

    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: initialDate,
      firstDate: firstDate,
      lastDate: lastDate,
    );

    if (picked != null && picked != _birthday) {
      setState(() {
        _birthday = picked;
      });
      widget.onDateChanged(picked);
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListTile(
      leading: Icon(Icons.calendar_today, color: Theme.of(context).colorScheme.secondary),
      title: Text(
        '生日: ${DateFormat("yyyy-MM-dd").format(_birthday)}',
        style: TextStyle(color: Theme.of(context).primaryColorDark),
      ),
      trailing: Icon(Icons.arrow_drop_down, color: Theme.of(context).colorScheme.secondary),
      onTap: () => _selectDate(context),
    );
  }
}
